/**
 * @Author: GuoXinyuan
 * @Date: 2021/5/28
 *
 * 自定义全局对象 使用sessionStorage存储
 * 只需在 globalObjectName 添加变量名对应字符串
 * set/get方法动态添加[如globalObjectName中添加‘Xxx’首字母大写,产生方法setXxx()/getXxx()]
 *  ps. 其他页面调用 set/get 时可能显示‘Unresolved function or method ...’
 * @constructor
 */

let Global = function() {

    /** --- 全局对象 --- */
    let globalObjectName = [
        "User", //用户全局对象
    ]

    this.globalObject = {}

    let _this = this;

    /** --- commen function */
    let getValue = function (argName) {
        let result = _this.globalObject[argName];
        if(result == null){
            result = JSON.parse(sessionStorage.getItem(argName));
        }
        return result;
    }

    let setValue = function (argName,arg){
        if(arg == null){
            sessionStorage.removeItem(argName);
            _this.globalObject[argName] = null;
        }
        else {
            let str = JSON.stringify(arg);
            sessionStorage.setItem(argName,str);
            _this.globalObject[argName] = JSON.parse(str);
        }
    }

    this.clearAll = function(){
        globalObjectName.forEach(function (name) {
           setValue(name,null);
        });
    }

    /** 初始化全局对象及get、set方法 */
    console.log("#Global: init global value.")
    globalObjectName.forEach(function (name) {
        _this.globalObject[name] = null;
        _this["get" + name] =  function () {
           return getValue(name);
        }
        _this["set" + name] = function (value) {
            setValue(name,value);
        }
    });

}

let global = new Global();
export default global;
